// // pages/login/login.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },
  getUserProfile(e) {
    // 通过code置换openid
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // console.log(res)
        if (res.code) {
          //发起网络请求
          wx.request({
            url: 'http://api_devs.wanxikeji.cn/api/codeExchangeOpenid',
            method: 'POST',
            data: {
              code: res.code //将code发给后台拿openid
            },
            success: function (res) {
              // 获取openid
              // console.log(res.data.data.openid);
              // console.log(res);
              wx.setStorageSync('openid', res.data.data.openid);
            }
          })
        }
      }
    });
    wx.showModal({
      title: '温馨提示',
      content: '正在请求您的个人信息',
      success(res) {
        if (res.confirm) {
          wx.getUserProfile({
            desc: "获取你的昵称、头像、地区等等",
            success: res => {
              console.log(res.userInfo.avatarUrl)

              let wxUserInfo = res.userInfo;
              wx.setStorageSync('userinfo', wxUserInfo);
              const userinfo = wx.getStorageSync('userinfo');
              const openid = wx.getStorageSync('openid');
              //注册
              wx.request({
                url: 'http://api_devs.wanxikeji.cn/api/register',
                method: 'POST',
                data: {
                  openid: openid,
                  nick_name: userinfo.nickName,
                  icon: userinfo.avatarUrl
                },
                success: function (res) {
                  // console.log(res);
                  let WXtoken = res.data.data.token;
                  wx.setStorageSync('token', WXtoken);
                }
              });
              const token = wx.getStorageSync('token');
              if (token == '') {
                //更新token
                wx.request({
                  url: 'http://api_devs.wanxikeji.cn/api/refreshToken',
                  method: 'POST',
                  data: {
                    openid: openid
                  },
                  success: function (res) {
                    // console.log(res);
                    wx.setStorageSync('token', res.data.data.token);
                    wx.setStorageSync('CXuserinfo', res.data.data);
                      wx.reLaunch({
                        url: '/pages/usercenter/usercenter',
                    })
                  }
                });
              }
              // url: '/pages/usercenter/usercenter',

            },
            fail: res => {
              //拒绝授权
              wx.showModal({
                title: '提示',
                content: '必须授权才能登录',
              })
              return;
            }
          })
        }
      }
    })
  },
  //点击返回
  returnMenu() {
    wx.navigateBack({
      delta: 1,
    })
  }
})
